package common

import (
	"github.com/jmoiron/sqlx"
)

func Rows(rows *sqlx.Rows) []map[string]interface{} {
	res := make([]map[string]interface{}, 0)
	if rows == nil {
		return res
	}
	for rows.Next() {
		dest := make(map[string]interface{})
		rows.MapScan(dest)
		for key, item := range dest {
			switch item.(type) {
			case []byte:
				dest[key] = string(item.([]byte))
			default:
			}
		}
		res = append(res, dest)
	}
	rows.Close()
	return res
}

func SqlInStrFromMap(items []map[string]interface{}, id string) string {
	ll := len(items)
	str := ""
	for i := 0; i < ll; i++ {
		initem := items[i]
		idItem, ok := initem[id]
		if !ok {
			continue
		}
		idStr := ValueToString(idItem, "")
		if len(idStr) == 0 {
			continue
		}
		if i > 0 {
			str = str + "','" + idStr
		} else {
			str = "('" + idStr
		}
	}
	if len(str) > 0 {
		str = str + "')"
	} else {
		str = "(-1)"
	}

	return str
}

func SqlInStrFromArrayString(items []string) string {
	ll := len(items)
	str := ""
	for i := 0; i < ll; i++ {
		idStr := ValueToString(items[i], "")
		if len(idStr) == 0 {
			continue
		}
		if i > 0 {
			str = str + "','" + idStr
		} else {
			str = "('" + idStr
		}
	}
	if len(str) > 0 {
		str = str + "')"
	} else {
		str = "(-1)"
	}

	return str
}
